<template>
  <div class="page-container-padding">
    <!-- 查询条件 -->
    <div style="display: flex; align-items: center">
      <span>
        <el-date-picker
          v-model="dateRange"
          style="width: 220px"
          type="daterange"
          size="mini"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        ></el-date-picker>
      </span>
      <span style="margin-left: 6px">
        <el-select v-model="statisticsType" style="width: 130px" size="mini">
          <el-option :value="0" label="默认统计方式"></el-option>
          <el-option :value="1" label="小组统计方式"></el-option>
        </el-select>
      </span>
      <span style="margin-left: 6px">
        <el-button type="primary" size="mini" @click="dateRangeQuery">
          统计
        </el-button>
      </span>
      <span style="margin-left: 6px">
        <el-button type="success" size="mini" @click="currentMonthQuery">
          计本月
        </el-button>
      </span>
      <span style="margin-left: 6px">
        <el-button type="infor" size="mini" @click="preMonthQuery">
          上一月
        </el-button>
      </span>
      <span style="margin-left: 6px">
        <el-button type="infor" size="mini" @click="nextMonthQuery">
          下一月
        </el-button>
      </span>
      <span style="margin-left: 6px">
        <el-button type="infor" size="mini" @click="yearQuery">全年</el-button>
      </span>
      <span style="margin-left: 6px">
        <el-button type="infor" size="mini" @click="preYearQuery">
          上一年
        </el-button>
      </span>
      <span style="margin-left: 6px">
        <el-button type="infor" size="mini" @click="nextYearQuery">
          下一年
        </el-button>
      </span>
    </div>
    <div style="margin-top: 6px">
      <el-checkbox v-model="onlyQhrbChecked" @change="qhrbCheckChange">只看期货日报的</el-checkbox>
    </div>
    <!-- 显示数据 -->
    <div style="width: 880px; margin-top: 10px">
      <div>文章撰写数量统计表</div>
      <el-table border stripe :data="statisticsList">
        <el-table-column prop="admin_name" label="姓名" width="100px">
          <template slot-scope="scope">
            <span style="cursor: pointer" @click="userCacheChange(scope.row)">
              {{ scope.row.admin_name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="total_count"
          label="总数量"
          align="right"
        ></el-table-column>
        <el-table-column
          prop="T01"
          label="专题文章"
          align="right"
        ></el-table-column>
        <el-table-column
          prop="T02"
          label="公众号"
          align="right"
        ></el-table-column>
        <el-table-column prop="T03" label="外发媒体" align="center">
          <el-table-column prop="qhrb_count" label="期货日报" align="right" />
          <el-table-column prop="T03_other" label="其他外发" align="right" />
          <el-table-column prop="T03" label="外发小计" align="right" />
        </el-table-column>
        <el-table-column
          prop="T11"
          label="其他"
          align="right"
        ></el-table-column>
        <el-table-column
          prop="level_count"
          label="评级"
          align="right"
        ></el-table-column>
      </el-table>
      <div style="color: #f34d37; font-size: 12px; margin-top: 2px">
        注：点击表中的用户名，可查看该人员的详细记录。
      </div>
    </div>

    <!-- 显示数据 -->
    <div style="margin-top:10px;">
      <div>文章撰写详细记录</div>
      <el-table border stripe :data="recordsShowList">
        <el-table-column prop="create_date" label="日期" width="100px"></el-table-column>
        <el-table-column prop="admin_name" label="姓名" width="100px"></el-table-column>
        <el-table-column prop="title" label="标题" width="300px"  show-overflow-tooltip></el-table-column>
        <el-table-column prop="words" label="字数" width="100px" align="right"></el-table-column>
        <el-table-column prop="level_flag" label="评级结果" width="90px" align="right"></el-table-column>
        <el-table-column prop="is_publish_zh" label="外发" width="50px" align="right"></el-table-column>
        <el-table-column label="附件" min-width="270px" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.annex">
              <vab-icon :icon="['fas', 'download']" @click="toDownloadAnnex(scope.row)"></vab-icon>
              <span class="annex-file" @click="toPreview(scope.row)">{{ scope.row.annex }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="期货日报" width="90px" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.article_type === 'T03' && scope.row.media_name==='期货日报'">
              是
            </span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-show="!onlyQhrbChecked"
        style="margin-top: 5px"
        background
        layout="total, prev, pager, next, jumper"
        :current-page.sync="page"
        :page-size="pageSize"
        :total="totalCount"
        @current-change="currentPageChange">
      </el-pagination>
    </div>

    <!-- 预览弹窗 -->
    <el-dialog width="900px" top="15px" :visible.sync="showDocxView" v-if="showDocxView" title="文章预览">
      <div style="height:calc(100vh - 128px);overflow-y:auto;">
        <div ref="docFile"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMonthDatePoint, getYearDatePoint, datetimeToStr } from '@/utils/datetimeUtils'
import { getArticleStatistics } from '@/api/departmentWork/articleWriting'
import { getFileBlob, downloadFile } from '@/api/fileHandler'
export default {
  data(){
    return {
      dateRange: [],
      statisticsType: 0,
        onlyQhrbChecked: false,
        statisticsCache: [],
      statisticsList: [],
      recordsCache: [],  // 存放统计表内的所有详情数据
      userRecordsCache: [],  // 当前点击的人员

      showFlag: 'total', // total or personal
      page: 1,
      pageSize:30,
      totalCount: 0,
      recordsShowList: [], // 当前显示的数据
      showDocxView: false,
    }
  },
  mounted() {
    this.setCurrentDates()
    this.queryPageData()
  },
  methods:{
    setCurrentDates(){
      let flag = new Date().getDate() < 4 ? 'previous' : 'current'
      this.dateRange = getMonthDatePoint(new Date(), flag)
    },
    qhrbCheckChange(flag) {
      // console.log(flag)
      if (flag) {
        // 显示有期货日报的数据
        let stShow = []
        for (let i=0; i<this.statisticsCache.length; i++) {
          const row = this.statisticsCache[i]
          if (row.qhrb_count && row.qhrb_count > 0) {
            stShow.push(JSON.parse(JSON.stringify(row)))
          }
        }
        // 计算合计行
        let tatalCount = 0
        let qhrbCount = 0
        for (let j=0; j<stShow.length; j++) {
          tatalCount += stShow[j].total_count
          qhrbCount += stShow[j].qhrb_count
        }
        stShow.push({
          user_id: -1,
          admin_name: '合计',
          total_count: tatalCount,
          qhrb_count: qhrbCount,
          level_count: ''
        })
        this.statisticsList = stShow

        // 详细记录
        let detailRow = []
        for (let k=0; k < this.recordsCache.length; k++) {
          const row = this.recordsCache[k]
          if (row.article_type === 'T03' && row.media_name === '期货日报') {
            detailRow.push(JSON.parse(JSON.stringify(row)))
          }
        }
        this.recordsShowList = detailRow
      } else {
        this.statisticsList = JSON.parse(JSON.stringify(this.statisticsCache))
        this.recordsShowList = JSON.parse(JSON.stringify(this.recordsCache))
      }
    },
    // 查询统计数据
    queryPageData(){
      const params = {
        start: datetimeToStr(this.dateRange[0], true, ''),
        end: datetimeToStr(this.dateRange[1], true, ''),
        st: this.statisticsType
      }
      this.pageDataLoading = true
      getArticleStatistics(params).then(res => {
        const data = res.data
        this.statisticsCache = data.statistics
            this.statisticsList = JSON.parse(
              JSON.stringify(this.statisticsCache)
            )
        this.recordsCache = data.records

        this.showFlag = 'total'
        this.totalCount = this.recordsCache.length
        this.page = 1
        this.showRecords(1)

        this.pageDataLoading = false
      }).catch(err => {
        this.pageDataLoading = false
      })
    },

    // 点击了统计表中的user
    userCacheChange(row){
      if (row.user_id == -1){
        this.userRecordsCache = this.recordsCache
      }else{
          this.userRecordsCache = this.recordsCache.filter(item => {
            if (this.onlyQhrbChecked) {
              return item.user_id === row.user_id && (item.article_type === 'T03' && item.media_name === '期货日报')
            } else {
              return item.user_id === row.user_id
            }
        })
      }
      

      this.showFlag = 'personal'
      this.totalCount = this.userRecordsCache.length
      this.page = 1
      this.showRecords(1)
    },

    currentPageChange(page){
      this.showRecords(page)
    },

    // 显示详情数据
    showRecords(page){
      const startIndex = (page-1)*this.pageSize
      if (this.showFlag === 'total'){
        this.recordsShowList = this.recordsCache.slice(startIndex, startIndex + this.pageSize)
      }else if (this.showFlag === 'personal'){
        this.recordsShowList = this.userRecordsCache.slice(startIndex, startIndex + this.pageSize)
      }
    },

    // 删除记录
    toDeleteArticle(row){
      this.$baseMessage('功能未上线!', 'info')
    },

    // 预览附件
    toPreview(row){
      if (row.annex_url.slice(-5) === '.docx'){
        this.showDocxView = true
        getFileBlob(row.annex_url).then(({data}) => {
          this.$docxView.renderAsync(data, this.$refs.docFile)
        })
      }else{
        this.toDownloadAnnex(row)
      }
    },

    // 下载附件
    toDownloadAnnex(row){
      if(!row.annex){return}
      downloadFile(row.annex_url)
    },

    // 指定日期范围查询
    dateRangeQuery(){
      this.queryPageData()
    },

    // 本月查询
    currentMonthQuery(){
      this.dateRange = getMonthDatePoint(new Date(), 'current')  // 当前月份
      this.queryPageData()
    },

    // 上一月查询
    preMonthQuery(){
      this.dateRange = getMonthDatePoint(this.dateRange[0], 'previous')
      this.queryPageData()
    },

    // 下一月查询
    nextMonthQuery(){
      this.dateRange = getMonthDatePoint(this.dateRange[0], 'next')
      this.queryPageData()
    },

    // 当前月份所在全年查询
    yearQuery(){
      let year = new Date(this.dateRange[0]).getFullYear()
      this.dateRange = getYearDatePoint(year, 'current')
      this.queryPageData()
    },

    // 上一年查询
    preYearQuery(){
      let year = new Date(this.dateRange[0]).getFullYear()
      this.dateRange = getYearDatePoint(year, 'previous')
      this.queryPageData()
    },

    // 下一年查询
    nextYearQuery(){
      let year = new Date(this.dateRange[0]).getFullYear()
      this.dateRange = getYearDatePoint(year, 'next')
      this.queryPageData()
    }
  }
}
</script>

<style scoped lang="scss">
.annex-file{
  color: #0073FC;
  cursor:pointer;
  margin-left:4px;
}
::v-deep {
  .docx-wrapper{
    background-color: #fefefe;
  }
}
</style>
